<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="求职者姓名" prop="userNickName" label-width="90px">
        <el-input v-model="queryParams.userNickName" placeholder="请输入求职者姓名" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="面试状态" prop="userIdleState">
        <el-select v-model="queryParams.userIdleState" placeholder="请选择面试状态" clearable>
          <el-option v-for="dict in idleState" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="面试发起时间" prop="createTime" label-width="100px">
        <el-date-picker clearable v-model="queryParams.createTime" type="date" value-format="YYYY-MM-DD"
          placeholder="请选择面试发起时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <el-button icon="Refresh" @click="handleTime">保护期设置</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="interviewList">
      <el-table-column label="求职者ID" align="center" prop="userId" />
      <el-table-column label="求职者姓名" align="center" prop="userNickName">
        <template #default="scope">
          {{ scope.row.userNickName }}
        </template>
      </el-table-column>

      <el-table-column label="意向等级" align="center" prop="level">
        <template #default="scope">
          <dict-tag :options="level" :value="scope.row.level" />
        </template>
      </el-table-column>
      <el-table-column label="面试状态" align="center" prop="userIdleState">

        <template #default="scope">
          <dict-tag :options="idle_state" :value="scope.row.userIdleState" />
        </template>
      </el-table-column>
      <el-table-column label="面试发起时间" align="center" prop="createTime" width="180">

        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

      <el-table-column label="距离保护期结束" align="center" prop="outTime">
        <template #default="scope">
          {{ scope.row.outTime }}
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">

        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:interview:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
            v-hasPermi="['manage:interview:remove']">退回公海</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改查看面试信息对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="interviewRef" :model="queryParams" :rules="rules" label-width="120px">
        <el-col :span="20">
          <el-form-item label="修改面试状态">
            <el-select v-model="form.userIdleState" placeholder="请选择" @change="handleChange">
              <el-option v-for="dict in idleState" :key="dict.value" :label="dict.label"
                :value="dict.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-form ref="staffForm" :model="data" size="medium" label-width="120px" label-position="left"
          v-if="showExtraForm">
          <el-divider content-position="left">补充员工信息</el-divider>
          <el-row gutter="15">
            <el-col :span="12">
              <el-form-item label-width="50px" label="民族" prop="queryParams.nation" :rules="rules.nation">
                <el-input v-model="queryParams.nation" placeholder="输入民族,例：壮族" clearable :style="{ width: '100%' }">
                </el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label-width="82px" label="归属部门" prop="queryParams.deptId" :rules="rules.deptId">
                <el-tree-select v-model="queryParams.deptId" :data="deptOptions"
                  :props="{ value: 'id', label: 'label', children: 'children' }" value-key="id" placeholder="请选择归属部门"
                  check-strictly />
              </el-form-item>
            </el-col>

            <el-col :span="24">
              <el-form-item label-width="82px" label="身份证号" prop="queryParams.staffNumber" :rules="rules.staffNumber">
                <el-input v-model="queryParams.staffNumber" placeholder="请输入身份证号" clearable :style="{ width: '100%' }"
                  maxlength="18" oninput="value=value.replace(/^\D*([0-9]\d*\.?\d{0})?.*$/,'$1')"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label-width="82px" label="银行卡号" prop="queryParams.cardNumber" :rules="rules.cardNumber">
                <el-input v-model="queryParams.cardNumber" placeholder="请输入银行卡号" clearable :style="{ width: '100%' }"
                  maxlength="19" oninput="value=value.replace(/^\D*([0-9]\d*\.?\d{0,0})?.*$/,'$1')"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="11">
              <el-form-item label="岗位" label-width="50px" prop="queryParams.postId" :rules="rules.postId">
                <el-select v-model="queryParams.postId" multiple placeholder="请选择" prop="queryParams.postId"
                  :rules="rules.postId">
                  <el-option v-for="item in postOptions" :key="item.postId" :label="item.postName" :value="item.postId"
                    :disabled="item.status == 1"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="13">
              <el-form-item label-width="82px" label="上级领导" prop="leaderNickName">
                <el-input v-model="form.leaderNickName" placeholder="上级领导" clearable
                  :style="{ width: '100%' }"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label-width="50px" label="工价" prop="queryParams.wages" :rules="rules.wages">
                <el-input v-model="queryParams.wages" placeholder="请输入工价(单位：每小时)" clearable :style="{ width: '100%' }"
                  maxlength="6" oninput="value=value.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label-width="43px" label="工种" prop="roleId">
                <el-select v-model="queryParams.roleId" placeholder="请选择工种" :style="{ width: '100%' }">
                  <el-option v-for="(item, index) in data.rules.roleId" :key="index" :label="item.label"
                    :value="item.value" :disabled="item.disabled"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label-width="78px" label="借支权限" prop="flag">
                <el-switch v-model="queryParams.flag" active-text="允许" inactive-text="禁止" :active-value='1'
                  :inactive-value='2' @change="borrowingFlagChange"></el-switch>
              </el-form-item>
            </el-col>

            <el-form :model="data" size="medium" label-width="120px" label-position="left" v-if="borrowingFlag">
              <el-row>
                <el-col :span="12">
                  <el-form-item label-width="82px" label="可借金额" prop="queryParams.amount" :rules="rules.amount">
                    <el-input v-model="queryParams.amount" placeholder="请输入可借金额" clearable :style="{ width: '90%' }"
                      maxlength="5" oninput="value=value.replace(/^\D*([0-9]\d*\.?\d{0,1})?.*$/,'$1')"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label-width="82px" label="可借次数" prop="queryParams.number" :rules="rules.number">
                    <el-input v-model="queryParams.number" placeholder="请输入可借次数" clearable :style="{ width: '90%' }"
                      maxlength="1" oninput="value=value.replace(/^\D*([0-9]\d*\.?\d{0})?.*$/,'$1')"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>

          </el-row>
        </el-form>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :title="titleTime" v-model="openTime" width="500px" append-to-body>
      <el-form :model="data" size="medium" label-width="120px" label-position="left">
        <el-table v-loading="loading" :data="timeList" @selection-change="handleSelectionChange">
          <el-table-column label="意向等级" align="center" prop="userLevel">

            <template #default="scope">
              <dict-tag :options="level" :value="scope.row.userLevel" />
            </template>
          </el-table-column>
          <!-- 添加保护期时长列 -->
          <el-table-column label="保护期时长" align="center" prop="outTime">

            <template #default="scope">
              <el-input v-model="scope.row.outTime" placeholder="输入保护期时长" clearable
                :style="{ width: '100%', textAlign: 'center' }">
              </el-input>
            </template>
          </el-table-column>
        </el-table>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitTime">确 定</el-button>
          <el-button @click="closeTime">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script setup name="Interview">
import { listInterview, getInterview, delInterview, addInterview, updateInterview } from "@/api/manage/interview";
import { deptTreeSelect, getUser } from "@/api/system/user";
import { listTime, getTime, delTime, addTime, updateTime } from "@/api/manage/time";
import { onMounted, reactive, ref } from "vue";

const { proxy } = getCurrentInstance();
const { idle_state, role_id, role_name, level } = proxy.useDict('idle_state', 'role_id', 'role_name', 'level');
const showExtraForm = ref(false);
const borrowingFlag = ref(false);
const postOptions = ref([]);

//打卡员工详细信息填充面板
const handleChange = (value) => {
  if (value == 4) {
    showExtraForm.value = true;
  } else {
    showExtraForm.value = false;
  }
};

//打卡借支权限详细信息填充面板
const borrowingFlagChange = (value) => {
  // 1表示允许借支
  if (value == 1) {
    borrowingFlag.value = true;
  } else {
    borrowingFlag.value = false;
  }
};

const idleState = [
  { label: "面试中", value: 2 },
  { label: "等待二次转厂", value: 3 },
  { label: "面试通过", value: 4 },
]

const interviewList = ref([]);
const timeList = ref([]);
const open = ref(false);
const openTime = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const titleTime = ref("");
const deptOptions = ref(undefined);
const interviewListTime = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    userIdleState: null,
    userNickName: null,
    createTime: null,
    cardNumber: undefined,
    staffNumber: undefined,
    nation: undefined,
    roleId: 1,
    flag: 2,
    deptId: undefined,
    postId: undefined,
    wages: undefined,
    amount: undefined,
    number: undefined,
    outTime: undefined,
  },
  rules: {
    deptId: [
      { required: true, message: "请选择部门", trigger: "change" }
    ],
    postId: [
      { required: true, message: "请选择岗位", trigger: "change" }
    ],
    wages: [
      { required: true, message: "请输入工价", trigger: "blur" },
      { min: 0, max: 6, message: "工价长度在 0 到 6 个字符", trigger: "blur" },
    ],
    cardNumber: [
      { required: true, message: "请输入银行卡号", trigger: "blur" },
      { min: 16, max: 19, message: "银行卡号长度在 16 到 19 个字符", trigger: "blur" },
    ],
    staffNumber: [
      { required: true, message: "请输入身份证号", trigger: "blur" },
      { min: 18, max: 18, message: "身份证号", trigger: "blur" },
    ],
    nation: [
      { required: true, message: "请输入民族", trigger: "blur" },
    ],
    roleId: [
      { label: "正式员工", value: 3 },
      { label: "小时工", value: 4 },
    ],
    amount: [
      { required: true, message: "请输入可借支金额", trigger: "blur" },
    ],
    number: [
      { required: true, message: "请输入可借支次数", trigger: "blur" },
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

async function outtime() {
  await Promise.all(interviewList.value.map(async (item, index) => {
    // 计算当前时间与生成时间的日期差
    // 将日期转换为毫秒
    const ms1 = new Date().getTime();
    const ms2 = new Date(item.createTime).getTime();
    // 计算毫秒差
    const millisecondsBetween = Math.abs(ms1 - ms2);
    // 转换为天数
    const daysBetween = millisecondsBetween / (1000 * 60 * 60 * 24);

    // 查询各意向等级的保护期时长
    const res = await getTime(item.level);
    interviewList.value[index].outTime = res.data.outTime - daysBetween.toFixed(0);
  }));
}

/** 查询查看面试信息列表 */
function getList() {
  loading.value = true;
  listInterview(queryParams.value).then(response => {
    interviewList.value = response.rows;
    total.value = response.total;
    loading.value = false;
    outtime()
  });
}

/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then(response => {
    deptOptions.value = response.data;
  });
};

// 取消按钮
function cancel() {
  open.value = false;
  handleChange();
  reset();
}

//关闭保护期设置
function closeTime() {
  openTime.value = false;
}

// 保护期数据列表
function resetTime() {
  form.value = {
    outTime: [],
    userLevel: []
  };
  proxy.resetForm("timeRef");
}

// 表单重置
function reset() {
  form.value = {
    interviewId: null,
    userIdleState: null,
    userId: null,
    userNickName: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,

    cardNumber: null,
    staffNumber: null,
    nation: null,
    roleId: null,
    flag: null,
    deptId: undefined,
    wages: undefined,
    postId: undefined,
    amount: undefined,
    number: undefined,
    leaderNickName: undefined
  };
  proxy.resetForm("interviewRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.interviewId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 打开保护期设置 */
function handleTime() {
  resetTime();
  openTime.value = true;
  titleTime.value = "保护期设置";
  listTime().then(response => {
    timeList.value = response.rows;
  });
}


/** 提交保护期修改 */
function submitTime() {
  // 上传修改数据
  console.log(timeList.value);
  updateTime(timeList.value).then(response => {
    proxy.$modal.msgSuccess("修改成功");
    openTime.value = false;
    resetTime();
    getList();
  });
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  getUser(row.userId).then(response => {
    postOptions.value = response.posts;
    // console.log(postOptions.value);
  });
  const _interviewId = row.interviewId || ids.value
  getInterview(_interviewId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改面试状态";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["interviewRef"].validate(valid => {
    if (valid) {
      if (form.value.interviewId != null) {
        queryParams.value.interviewId = form.value.interviewId;
        queryParams.value.userIdleState = form.value.userIdleState;
        queryParams.value.userNickName = form.value.userNickName;
        queryParams.value.userId = form.value.userId;
        updateInterview(queryParams.value).then(response => {
          console.log("提交表单" + queryParams.value);
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          resetQuery();
          getList();
        });
      } else {
        addInterview(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _interviewIds = row.interviewId || ids.value;
  proxy.$modal.confirm('确定将"' + row.userNickName + '"的资源返回公海？').then(function () {
    return delInterview(_interviewIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("操作成功");
  }).catch(() => { });
}

getDeptTree();

onMounted(() => {
  getList();
})
// getList();
</script>
